package com.gitee.sop.layui.adminserver.module.background.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.sop.layui.adminserver.module.background.admin.entity.SysUser;
import com.gitee.sop.layui.adminserver.module.background.admin.entity.SysUserFunctionRoleRelation;
import com.gitee.sop.layui.adminserver.module.background.admin.mapper.SysUserFunctionRoleRelationMapper;
import com.gitee.sop.layui.adminserver.module.background.admin.service.SysDataModifyLockService;
import com.gitee.sop.layui.adminserver.module.background.admin.service.SysUserFunctionRoleRelationService;
import com.gitee.sop.layui.adminserver.module.background.admin.util.SysDataModifyLockUtil;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 功能角色和用户的映射  服务实现类
 * </p>
 *
 * @author admin
 * @since 2019-11-28
 */
@Service
public class SysUserFunctionRoleRelationServiceImpl extends ServiceImpl<SysUserFunctionRoleRelationMapper, SysUserFunctionRoleRelation> implements SysUserFunctionRoleRelationService {
    @Lazy
    @Resource
    private SysDataModifyLockService sysDataModifyLockService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setAuthority(String userUuid, List<Integer> fnRoleIdList) {
        sysDataModifyLockService.checkLocked(SysDataModifyLockUtil.generateKey(SysUser.class, userUuid));
        //删除角色
        this.baseMapper.deleteByUserUuid(userUuid);
        if (!fnRoleIdList.isEmpty()) {
            List<SysUserFunctionRoleRelation> list = fnRoleIdList.stream().collect(ArrayList::new, (res, ele) -> res.add(new SysUserFunctionRoleRelation(userUuid, ele)), (l, r) -> {
            });
            saveBatch(list);
        }

    }

    @Override
    public List<Integer> getFunctionRoleIdByUserUuid(String userUuid) {
        return this.baseMapper.selectFunctionRoleIdByUserUuid(userUuid);
    }

    @Override
    public int countInFunctionRoleIdList(List<Integer> functionRoleIdList) {
        return baseMapper.countInFunctionRoleIdList(functionRoleIdList);
    }

    @Override
    public void removeByUserUuid(String uuid) {
        baseMapper.deleteByUserUuid(uuid);
    }

}
